//
//  AdView.m
//  AdImage
//
//  Created by Burn on 2019/7/23.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "AdView.h"
#import "PageContro.h"

@interface AdView ()<UIScrollViewDelegate>

@property(copy,nonatomic)loadImage loadIMG;
@property(strong,nonatomic) NSMutableArray *models;
@property(strong,nonatomic) NSMutableArray *imageViews;
@property(assign,nonatomic) NSInteger currentPage;
@property(strong,nonatomic) UIScrollView *scrollView;
@property(strong,nonatomic) NSTimer *timer;
@property(strong,nonatomic) PageContro *pageContro;

@end
static NSInteger radio = 10;
@implementation AdView

- (instancetype)initWithFrame:(CGRect)frame loadImage:(loadImage)loadIMG{
    if (self == [super initWithFrame:frame]) {
        self.loadIMG = loadIMG;
        [self addSubview:self.scrollView];
        [self addSubview:self.pageContro];
    }
    return self;
}

- (void)setAdWith:(NSArray<AdImageProtocol> *)adModels{
    self.models = [adModels mutableCopy];
    
    for (UIImageView *imagev in self.imageViews) {
        [imagev removeFromSuperview];
    }
    [self.imageViews removeAllObjects];
    
    NSInteger baseCount = adModels.count;
    NSInteger count = baseCount;
    if (baseCount > 1) {
        count = baseCount * radio;
    }
    
    for (int i = 0; i < count; i++) {
        id<AdImageProtocol> model = adModels[i % baseCount];
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.tag = adModels.count;
        
        if (self.loadIMG) {
            self.loadIMG(imageView, model.url);
        }
        /*
        UILabel *label = [[UILabel alloc]init];
        label.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:.5];
        label.font = [UIFont systemFontOfSize:17];
        label.numberOfLines = 0;
        [imageView addSubview:label];
         */
        
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)];
        [imageView addGestureRecognizer:labelTapGestureRecognizer];

        [self.scrollView addSubview:imageView];
        
        [self.imageViews addObject:imageView];
    }
    
    self.pageContro.numberOfPages = adModels.count;
    
    //  布局
    [self setNeedsLayout];
    
    //  根据条件激活Timer
    if (adModels.count > 1) {
        [self setUpTimer];
    }else{
        [_timer invalidate];
        _timer = nil;
        _pageContro.hidden = YES;
    }
    
}

- (void)click:(UIGestureRecognizer *)ges{
    UIImageView *imageView = (UIImageView *)ges.view;
    NSInteger tag = imageView.tag % self.models.count;
    id<AdImageProtocol> model = self.models[tag];
    if ([self.delegate respondsToSelector:@selector(clickAdWith:)]) {
        [self.delegate clickAdWith:model];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    NSInteger count = self.imageViews.count;
    
    for (int i = 0; i < count; i++) {
        UIImageView *imageView = self.imageViews[i];
        imageView.frame = CGRectMake(i * width, 0, width, height);
        
        /*
        let leftLabel : UILabel = adPictures[i].subviews[0] as! UILabel
        leftLabel.frame = CGRect (x: width / 5 * 4, y: 0, width: width / 5, height: heigth)
         */
        
    }
    self.scrollView.contentSize = CGSizeMake(self.imageViews.count * width, 0);
    
}

- (void)setUpTimer{
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerAction];
    }];
    
}

- (void)timerAction{
    NSInteger page = self.currentPage + 1;
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * page, 0) animated:YES];
    NSLog(@"%ld",self.currentPage);
}

#pragma mark - UIScrollViewDelegate
- (void)caculateCurrnetPage:(UIScrollView *)scrollView{
    if (self.models.count == 0) {
        return;
    }
    
    if (self.models.count == 1) {
        self.currentPage = 1;
        return;
    }
    
    NSInteger min = self.models.count * (radio / 2);
    NSInteger max = self.models.count * (radio / 2) + 1;
    
    //  获取下标
    NSInteger page = scrollView.contentOffset.x / scrollView.frame.size.width;
    self.pageContro.currentPage = page % self.models.count;
    NSLog(@"currentPage = %ld",page % self.models.count);
    
    if (page < min || page > max) {
        page = min + page % self.models.count;
        self.scrollView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0);
    }
    self.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.timer == nil) { return; }
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.models.count > 1) {
        [self setUpTimer];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self caculateCurrnetPage:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self caculateCurrnetPage:scrollView];
}

- (NSMutableArray *)models{
    if (!_models) {
        _models = [NSMutableArray array];
    }
    return _models;
}

- (NSMutableArray *)imageViews{
    if (!_imageViews) {
        _imageViews = [NSMutableArray array];
    }
    return _imageViews;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        [_scrollView setPagingEnabled:YES];
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}


- (PageContro *)pageContro{
    if (!_pageContro) {
        _pageContro = [[PageContro alloc]init];
        _pageContro.pageIndicatorTintColor = [UIColor grayColor];
        _pageContro.currentPageIndicatorTintColor = [UIColor orangeColor];
        _pageContro.hidesForSinglePage = YES;
        _pageContro.currentPage = 0;
        _pageContro.location = LocationRight;
        _pageContro.frame = CGRectMake(0, self.frame.size.height - 20, self.frame.size.width, 20);
    }
    return _pageContro;
}


-(void)dealloc{
    NSLog(@"ADVIEW - dealloc");
    [_timer invalidate];
    _timer = nil;
}


@end
